import Taro, { Component, Config } from '@tarojs/taro'
import { View, Image, Text, Swiper, SwiperItem } from '@tarojs/components'
import classnames from 'classnames'

import { observer, inject } from '@tarojs/mobx'

import toNumber from 'lodash/toNumber'

// components
import MyQuantity from '../../components/common/MyQuantity'

// styles
import './index.scss'

// store
import store from './store'

type DataProps = {
  productDetailStore: typeof store
}

type EventProps = {}

type State = {}

type Props = DataProps & EventProps

@inject(() => {
  return { productDetailStore: store }
})
@observer
class ProductDetailPage extends Component<Props, State> {
  changeQuantity = store.changeQuantity
  comfirm = store.comfirm
  /**
   * 指定config的类型声明为: Taro.Config
   *
   * 由于 typescript 对于 object 类型推导只能推出 Key 的基本类型
   * 对于像 navigationBarTextStyle: 'black' 这样的推导出的类型是 string
   * 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型
   */
  config: Config = {
    navigationBarTitleText: '商品详情',
    backgroundColor: '#F3F2ED',
  }

  constructor(props: Props) {
    super(props)
  }

  async componentWillPreload(params: any) {
    const productId = toNumber(params.productId)
    await store.init({ productId })
  }

  render() {
    const { product, totalPrice, buyQuantity } = this.props.productDetailStore
    const name = product ? product.name : ''
    const price = product ? product.shoppPrice : ''
    const imageInfos = product ? product.imageInfos : []

    return (
      <View className='product-detail-page'>
        <View className='product-detail-page__card'>
          <View className='product-detail-page__card-title'>{name}</View>

          <Swiper className='product-detail-page__card-photo' indicatorDots circular>
            {imageInfos.map(img => {
              return (
                <SwiperItem key={img.id}>
                  <Image src={img.imgUrl} />
                </SwiperItem>
              )
            })}
          </Swiper>

          <View className='product-detail-page__card-bottom'>
            <Text className='product-detail-page__card-price'>¥{price}</Text>
            <View className='product-detail-page__card-quantity'>
              <MyQuantity value={buyQuantity} onChange={this.changeQuantity} />
            </View>
          </View>
        </View>

        <View className='product-detail-page__bottom'>
          <View className='product-detail-page__total-price'>¥{totalPrice}</View>
          <View
            className={classnames('product-detail-page__confirm', buyQuantity <= 0 && 'disable')}
            onClick={this.comfirm}
          >
            选好了
          </View>
        </View>
      </View>
    )
  }
}

// #region 导出注意
//
// 经过上面的声明后需要将导出的 Taro.Component 子类修改为子类本身的 props 属性
// 这样在使用这个子类时 Ts 才不会提示缺少 JSX 类型参数错误
//
// #endregion

export default ProductDetailPage
